<template>
  <div class="content-container">
    <p-tooltip placement="topLeft">
      <template slot="title">
        <div v-if="isEdit">
          <div v-for="(val, key) in value" :key="key">
            <span>{{ key }} : </span>
            <span>{{ val }}</span>
          </div>
        </div>
        <div v-else>{{ formatValue }}</div>
      </template>
      <span class="ellipsis" :style="{ width: width }">{{ formatValue }}</span>
    </p-tooltip>
  </div>
</template>

<script>
import Decimal from 'decimal.js';
import { isObject } from '@/utils/is';

export default {
  props: {
    value: {
      type: Object,
      default: () => ({}),
    },
    width: {
      type: String,
      default: '80px',
    },
    toFixed: {
      type: Number,
      default: undefined,
    },
    min: {
      type: Number,
      default: undefined,
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    formatValue() {
      if (isObject(this.value)) {
        return Object.keys(this.value).reduce((pre, cur) => {
          pre += Number(this.value[cur] || 0);
          return pre;
        }, 0);
      } else {
        return this.value;
      }
    },
  },
  methods: {
    handleInput(e) {
      const value = e.target.value;
      let copy = value?.replace(/[^0-9]/gi, '');
      if (copy) {
        copy = Number(copy);
      }
      e.target.value = copy;
      this.$emit('change', copy);
    },
    handleBlur(e) {
      let value = e.target.value;
      if (this.toFixed !== undefined && value) {
        value = new Decimal(value).toFixed(2);
      }
      if (this.min !== undefined && Number(value) <= this.min) {
        value = '';
      }
      e.target.value = value;
      this.$emit('change', value);
    },
  },
};
</script>

<style lang="less" scoped>
.content-container {
  width: 100%;
  display: flex;
  align-items: center;
  .content {
    margin-right: auto;
  }
  .icon {
    margin-left: 8px;
  }
  .ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    word-break: break-all;
  }
}
</style>
